package com.cookbook.controller;

import com.cookbook.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author 毛川
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    private String makeFileName(String filename) {
        int suffixPointOffset = filename.lastIndexOf('.');
        String suffix = "";
        if (suffixPointOffset != -1) {
            suffix = filename.substring(suffixPointOffset);
        }

        return UUID.randomUUID().toString() + suffix;
    }

    private String hashPath(String filename) {
        //得到文件名的hashCode的值，得到的就是filename这个字符串对象在内存中的地址
        int hashcode = filename.hashCode();
        int dir1 = hashcode & 0xf;  //0--15
        int dir2 = (hashcode & 0xf0) >> 4;  //0-15
        //构造新的保存目录
        return "/" + dir1 + "/" + dir2;
    }

    private String makePath(String savePath) {
        //File既可以代表文件也可以代表目录
        File file = new File(savePath);
        //如果目录不存在
        if (!file.exists()) {
            //创建目录
            file.mkdirs();
        }
        return savePath;
    }

    @RequestMapping(value = "/images", method = RequestMethod.POST)
    @ResponseBody
    public String images(@RequestParam MultipartFile[] images, HttpSession session) {
        return save(Arrays.asList(images), session);
    }

    @RequestMapping(value = "/images1", method = RequestMethod.POST)
    @ResponseBody
    public String images1(
            @RequestParam MultipartFile image0,
            @RequestParam(required = false) MultipartFile image1,
            @RequestParam(required = false) MultipartFile image2,
            @RequestParam(required = false) MultipartFile image3,
            @RequestParam(required = false) MultipartFile image4,
            @RequestParam(required = false) MultipartFile image5,
            @RequestParam(required = false) MultipartFile image6,
            @RequestParam(required = false) MultipartFile image7,
            @RequestParam(required = false) MultipartFile image8,
            @RequestParam(required = false) MultipartFile image9,
            @RequestParam(required = false) MultipartFile image10,
            HttpSession session) {
        List<MultipartFile> images = new ArrayList<MultipartFile>();
        images.add(image0);
        if (image1 != null) images.add(image1);
        if (image2 != null) images.add(image2);
        if (image3 != null) images.add(image3);
        if (image4 != null) images.add(image4);
        if (image5 != null) images.add(image5);
        if (image6 != null) images.add(image6);
        if (image7 != null) images.add(image7);
        if (image8 != null) images.add(image8);
        if (image9 != null) images.add(image9);
        if (image10 != null) images.add(image10);
        return save(images, session);
    }

    private String save(List<MultipartFile> images, HttpSession session) {
        for (MultipartFile image : images) {
            String originFilename = image.getOriginalFilename();
            if (!isAvailableSuffix(originFilename))
                return Result.format(
                        Result.FILE_SUFFIX_NOT_SUPPORTED,
                        "不支持的文件后缀" + originFilename);
        }

        try {
            List<String> imageUris = new ArrayList<String>();
            String savePath = session.getServletContext().getRealPath("/images");
            for (MultipartFile image : images) {
                String originFilename = image.getOriginalFilename();
                String realFilename = makeFileName(originFilename);
                String realFilePath = hashPath(realFilename);
                String uri = "/images" + realFilePath + "/" + realFilename;

                realFilePath = makePath(savePath + realFilePath);
                File file = new File(realFilePath, realFilename);
                image.transferTo(file);
                imageUris.add(uri);
            }
            return Result.success(imageUris);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
    }

    private boolean isAvailableSuffix(String filename) {
        final String[] suffixes = {
                "jpg", "png", "gif", "jpeg", "bmp"
        };

        for (String suffix : suffixes) {
            if (filename.endsWith(suffix))
                return true;
        }
        return false;
    }
}
